package editor.cn;

//Given an array nums of n integers and an integer target, find three integers i
//n nums such that the sum is closest to target. Return the sum of the three integ
//ers. You may assume that each input would have exactly one solution. 
//
// 
// Example 1: 
//
// 
//Input: nums = [-1,2,1,-4], target = 1
//Output: 2
//Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
// 
//
// 
// Constraints: 
//
// 
// 3 <= nums.length <= 10^3 
// -10^3 <= nums[i] <= 10^3 
// -10^4 <= target <= 10^4 
// 
// Related Topics 数组 双指针 
// 👍 631 👎 0

import java.util.Arrays;

public class ThreeSumClosest{
    public static void main(String[] args) {
        Solution solution = new ThreeSumClosest().new Solution();
        int[] nums = {1,1,1,0};
        System.out.println(solution.threeSumClosest(nums, -100));
    }

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int standard = 0;
        int result = 0;
        standard =Math.abs(target - nums[0]-nums[1]-nums[nums.length-1]) ;
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            if (l >= r) {
                break;
            }
            int sum;
            while (l < r) {
                sum = nums[i] + nums[l] + nums[r];
                if (standard >= Math.abs(target - sum)) {
                    standard =Math.abs(target - sum) ;
                    result = sum;
                }
                if (sum > target) {
                    r--;
                    continue;
                } else if (sum < target) {
                    l++;
                    continue;
                } else {
                    return sum;
                }
            }
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}